package com.hcb.micro.controller;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hcb.micro.sdk.OSSUPUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.UploadFileRequest;
import com.aliyun.oss.model.UploadFileResult;
import com.hcb.micro.bean.base.OutHead;
import com.hcb.micro.dto.ReturnUploadImage;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("file")
public class FileController {
    private static String accessKeyId = OSSUPUtil.ACCESS_KEY_ID;
    private static String accessKeySecret = OSSUPUtil.ACCESS_KEY_SECRET;
    private static String bucketName = OSSUPUtil.BUCKET_NAME;
    private static String endpoint = OSSUPUtil.END_POINT;
    private static String domainName = OSSUPUtil.DOMAIN_NAME;
    private static String folderPath = OSSUPUtil.FOLDER_PATH;


    private final String imageUrl = "http://" + bucketName + "." + domainName + "/";

    private transient final Logger logger = Logger.getLogger(getClass());

    /**
     * 根目录
     */

    //private static String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    //private static String accessKeyId = "LTAIEBYdbuuY3HCI";
    //private static String accessKeySecret = "2U6js4HyZzNV7BUB01nE2hEyx5ACh1";
    //private static String bucketName = "feichs";
    //public static final String imageUrl = "http://feichs.oss-cn-beijing.aliyuncs.com/";
/*	private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
	private static String accessKeyId = "rvCyNiasyIq1JGHD";
	private static String accessKeySecret = "VzKWi0s3y3CXSzqKr7b8E1NBmYGNgo";
	private static String bucketName = "bucket20160601";
	public static final String imageUrl = "http://bucket20160601.oss-cn-hangzhou.aliyuncs.com/";
*/	
	/*@RequestMapping(value = "uploadFile", method = RequestMethod.POST)
	@ResponseBody
	public String uploadFile() {
		JSONObject json = new JSONObject();
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		int right = 1;
		if (bodyInfo.get("file") == null || "".equals(bodyInfo.get("file"))) {
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}
		
		BufferedImage image = null;
		String imageResult = "";
		try {
			
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	        MultipartFile multipartFile = multipartRequest.getFile("file");
			
	       	image = ImageIO.read(multipartFile.getInputStream()); //读取连接的流，赋值给BufferedImage对象
	       	
	       	Random random = new Random();
	    	String number = Long.toHexString(Long.valueOf(random.nextInt(10) + "" + System.currentTimeMillis() + "" + random.nextInt(10)));
	       	
   			String imageName = "image"+number+".jpg";
			OSSUPUtil.uploadIMG(imageName,image);
			imageResult = "http://bucket20160601.oss-cn-hangzhou.aliyuncs.com/"+imageName;
		} catch (Exception e) {
			e.printStackTrace();
	    	json.put("result", "1");
			json.put("description", "文件上传失败");
			return buildReqJsonObject(json);
		}     
		
		json.put("imageResult", imageResult);
    	json.put("result", "0");
		json.put("description", "文件上传成功");
		
		return buildReqJsonObject(json);
	}
	
	@RequestMapping(value = "uploadImage1", method = RequestMethod.POST)
	@ResponseBody
	public String uploadImage() {
		JSONObject json = new JSONObject();
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		int right = 1;
		if (bodyInfo.get("file") == null || "".equals(bodyInfo.get("file"))) {
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}
		
		Random random = new Random();
		String number = Long.toHexString(Long.valueOf(random.nextInt(10) + "" + System.currentTimeMillis() + "" + random.nextInt(10)));
		BufferedImage image = null;
		String imageResult = "";
		try {
			URL u = new URL(bodyInfo.getString("file"));
			image = ImageIO.read(u);
   			String imageName = "CC_PRODUCT_"+number+"1.jpg";
			OSSUPUtil.uploadIMG(imageName,image);
			imageResult = "http://bucket20160601.oss-cn-hangzhou.aliyuncs.com/"+imageName;
		} catch (Exception e) {
			e.printStackTrace();
	    	json.put("result", "1");
			json.put("description", "文件上传失败");
			return buildReqJsonObject(json);
		}
		
		json.put("imageResult", imageResult);
    	json.put("result", "0");
		json.put("description", "文件上传成功");
		
		return buildReqJsonObject(json);
	}*/

    //上传文件
    @RequestMapping(value = "uploadImage", method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file) throws Exception {
        JSONObject json = new JSONObject();
        String fileUrl = "";
        String loghead = "通用接口-上传图片:";
        // 判断文件是否为空
        if (!file.isEmpty()) {
            //校验文件类型
            String originName = file.getOriginalFilename();
            String[] types = originName.split("\\.");
            String origin = types[0];
            String type = null == types[types.length - 1] ? "" : types[types.length - 1];

            Random random = new Random();
            String number = Long.toHexString(Long.valueOf(random.nextInt(10) + "" + System.currentTimeMillis() + "" + random.nextInt(10)));
            String contentType = file.getContentType();
            String fileName = origin + '-' + number;

            long fileSize = file.getSize();
            System.out.println(loghead + "fileInfo:fileName=" + fileName + "&fileSize=" + fileSize);
            if (fileSize <= 0) {
                System.out.println(loghead + "上传失败:文件为空");
                json.put("result", "1");
                json.put("description", "上传失败:文件为空");
                return buildReqJsonObject(json);
            } else if (fileSize > (500 * 1024)) {
                System.out.println(loghead + "上传失败:文件大小不能超过500K");
                json.put("result", "1");
                json.put("description", "上传失败:文件大小不能超过500K,请压缩后上传");
                return buildReqJsonObject(json);
            }
            logger.info("文件符合条件，开始上传oss。endpoint=" + endpoint + ", accessKeyId=" + accessKeyId + ", accessKeySecret=" + accessKeySecret);
            // 创建OSSClient实例
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            // 上传文件
            ObjectMetadata metadata = new ObjectMetadata();

            metadata.setContentType(file.getContentType());

            PutObjectResult result = ossClient.putObject(bucketName, folderPath + fileName + "." + type,
                    file.getInputStream(), metadata);

            // 关闭client
            ossClient.shutdown();
            fileUrl = imageUrl + URLEncoder.encode(fileName + "." + type, "UTF-8");
            json.put("fileUrl", imageUrl + folderPath + URLEncoder.encode(fileName + "." + type, "UTF-8"));
            json.put("result", "0");
            json.put("description", "1");
            return buildReqJsonObject(json);
        } else {
            json.put("result", "1");
            json.put("description", "1");
            return buildReqJsonObject(json);
        }
    }


    protected String buildReqJsonObject(Object msgs) {
        com.alibaba.fastjson.JSONObject jo = new com.alibaba.fastjson.JSONObject();
        jo.put("head", getDefaultOutHead());
        jo.put("body", msgs);
        return jo.toJSONString();
    }

    protected OutHead getDefaultOutHead() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String time = format.format(date);
        return new OutHead().setReturnCode("000").setReturnDescription("验证通过").setSysTime(time);
    }

    /**
     * lxy 微信获取 再上传
     *
     * @param request
     * @return
     */
	/*@RequestMapping("imageweixin")
	@ResponseBody
	public String weixinimg(HttpServletRequest request, HttpServletResponse response, HttpSession session,String serverId) {
		if ( serverId!=null ) {
		    String accessToken=WeixinMessageDigestUtil.getAccessToken(CommonConstant.appid, CommonConstant.secret);
			// 创建OSSClient实例
			String bucketName = "bucket20160601";
			OSSClient ossClient = new OSSClient("http://oss-cn-hangzhou.aliyuncs.com", "rvCyNiasyIq1JGHD","VzKWi0s3y3CXSzqKr7b8E1NBmYGNgo");
			String requestUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";  
			requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", serverId);  
			try {
				String attachmentUuid = this.generateFileName(serverId);
				URL url = new URL(requestUrl);  
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
				conn.setDoInput(true);  
				conn.setRequestMethod("GET");  
				conn.connect();
				InputStream input = conn.getInputStream();
				ObjectMetadata metadata = new ObjectMetadata();
				metadata.setContentType(conn.getContentType());
				PutObjectResult result = ossClient.putObject(bucketName, attachmentUuid+"." +"jpg",input, metadata);
	        	  
				String  imgurl=   "http://"+bucketName+".oss-cn-beijing.aliyuncs.com/"+attachmentUuid+"." +"jpg";
				System.out.println("imgurlNum---------------+++++++--------------:"+imgurl);
				return imgurl;
			} catch (Exception e) {
				//handle exception
				e.printStackTrace();
			}
		}
		return "no";
	}*/
	
	/*@RequestMapping(value = "downloadFile", method = RequestMethod.POST)
	@ResponseBody
	public String downloadFile() {
		JSONObject json = new JSONObject();
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		int right = 1;
		if (bodyInfo.get("imageUrl") == null || "".equals(bodyInfo.get("imageUrl"))) {
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}
		
		String imageResult = "";
		try {
			imageResult = OSSUPUtil.getImgURl(bodyInfo.getString("imageUrl"));
		} catch (Exception e) {
			e.printStackTrace();
	    	json.put("result", "1");
			json.put("description", "文件下载失败");
			return buildReqJsonObject(json);
		}     
		
		json.put("tempFilePath", imageResult);
    	json.put("result", "0");
		json.put("description", "文件下载成功");
		
		return buildReqJsonObject(json);
	}*/

    // 上传文件
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    @ResponseBody
    public String uploadImage(HttpServletRequest request, HttpServletResponse response)
            throws IllegalStateException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        ServletContext servletContext = request.getSession().getServletContext();
        System.out.println("servletContext:" + servletContext);
        String uploadPath = servletContext.getRealPath("/") + "ueditor/jsp/upload/image/";
        System.out.println("uploadPath:" + uploadPath);
        ReturnUploadImage rui = null;// 这个是UEditor需要的返回值内容，UEditor要的返回值需要封装成Json格式
        // 转型为MultipartHttpRequest：
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得文件：
        MultipartFile file = multipartRequest.getFile("upfile"); // UEditor传到后台的是这个upfile，其他的文件上传，应该也差不多是这个，还没去研究，断点一下就知道了
        String OriginalFilename = file.getOriginalFilename();

        System.out.println("OriginalFilename:" + OriginalFilename);

        String fileSuffix = OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1).toLowerCase();
        String newname = "";
        SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
        String times = sf_.format(new Date());
        newname = times + (int) (Math.random() * (99999 - 10000) + 10000) + "." + fileSuffix;
        // 写入文件
        File imageFile = new File(uploadPath, newname);
        file.transferTo(imageFile);
        // 现在获取了File接下来要上传到OSS上
        if (imageFile != null) {
            rui = new ReturnUploadImage();
            rui.setTitle(imageFile.getName());// 这里需要设置文件名称如：xxx.jpg
            rui.setOriginal(imageFile.getName());// 这里需要设置文件名称如：xxx.jpg
            // 判断文件是否为图片文件
            // 上传文件(先保存到磁盘，这样对磁盘比较伤，每次上传都要先保存到磁盘，然后再删除)
            String str = partUpload(uploadPath + newname, newname);// 这里是自己封装的OSS，上传到OSS上面
            System.out.println("OSSstr:" + str);
            rui.setUrl(str);
            rui.setState("SUCCESS");// 这里上传成功的话一定要设置大写的 //
            // SUCCESS，失败还没测试，猜应该是FAIL，回头再去官网找找
            // 判断临时存放的文件是否存在
            if (imageFile.exists()) {
                // 删除临时存放的文件
                imageFile.delete();
            }
        }
        String result = JSON.toJSONString(rui);// 这边就是为了返回给UEditor做的格式转换
        System.out.println("result:" + result);
        response.getWriter().write(result);
        return null;
    }

    /**
     * 断点续传上传
     *
     * @param fileAbsolutePath
     * @return
     */
    public static String partUpload(String fileAbsolutePath, String fileName) {//, String packageName
        // 设置断点续传请求
        UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, folderPath + fileName);
        // 指定上传的本地文件
        uploadFileRequest.setUploadFile(fileAbsolutePath);
        // 指定上传并发线程数
        uploadFileRequest.setTaskNum(8);
        // 指定上传的分片大小
        uploadFileRequest.setPartSize(1 * 1024 * 1024);
        // 开启断点续传
        uploadFileRequest.setEnableCheckpoint(true);
        // 断点续传上传
        ///client.uploadFile(uploadFileRequest);
        try {
            // 断点续传上传
            // 创建OSSClient实例
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);
            return null != uploadResult ? uploadResult.getMultipartUploadResult().getLocation() : "";


        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return "";
        }
    }
}
